<template>
  <div class="user-container">
    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-card">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="用户名、昵称、邮箱"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="角色">
          <el-select
            v-model="searchForm.roleId"
            placeholder="请选择角色"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="0" />
            <el-option label="禁用" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card shadow="hover" class="main-card">
      <template #header>
        <div class="card-header">
          <h3>用户管理</h3>
          <div class="header-buttons">
            <el-button
              type="danger"
              :icon="Delete"
              :disabled="selectedUsers.length === 0"
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
            <el-button type="primary" :icon="Plus" @click="handleAdd" v-has = "'system:user:add'">
              新增用户
            </el-button>
          </div>
        </div>
      </template>

      <!-- 用户表格 -->
      <el-table
        v-loading="loading"
        :data="userList"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column prop="id" label="ID" width="80" align="center" />

        <el-table-column prop="username" label="用户名" width="120" />

        <el-table-column prop="nickname" label="用户昵称" width="120" />

        <el-table-column prop="email" label="邮箱" width="200" show-overflow-tooltip />

        <el-table-column prop="phone" label="手机号" width="130" />

        <el-table-column prop="roleName" label="角色" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.roleId)">
              {{ row.roleName }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <div class="status-wrapper">
              <!-- 状态开关 -->
              <el-switch
                :model-value="getStatusValue(row.status) === 0"
                @change="(value:any) => handleStatusChange(row, value ? 0 : 1)"
              />
              <!-- 状态文字（调试用，可以后期删除） -->
              <div class="status-debug">
                {{ getStatusText(row.status) }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" width="160" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="updateTime" label="更新时间" width="160" align="center">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              :icon="Edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="formRules"
        label-width="80px"
        class="user-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="userForm.username"
                placeholder="请输入用户名"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickname">
              <el-input
                v-model="userForm.nickname"
                placeholder="请输入用户昵称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="!isEdit">
          <el-col :span="24">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="userForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="userForm.email"
                placeholder="请输入邮箱"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="userForm.phone"
                placeholder="请输入手机号"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="roleId">
              <el-select
                v-model="userForm.roleId"
                placeholder="请选择角色"
                style="width: 100%"
              >
                <el-option
                  v-for="role in roleList"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="userForm.status">
                <el-radio :label="0">启用</el-radio>
                <el-radio :label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
  import {
    Search,
    Refresh,
    Plus,
    Edit,
    Delete,
    Right
  } from '@element-plus/icons-vue'

  // 导入API和类型
  import {
    getUserListAPI,
    addUserAPI,
    updateUserAPI,
    deleteUserAPI,
    batchDeleteUserAPI,
    updateUserStatusAPI,
    getRoleListAPI
  } from '@/api/system/user/user.ts'
  import type { UserInfo, UserSearchParams, UserFormData, RoleInfo } from '@/api/system/user/types.ts'

  // 响应式数据
  const loading = ref(false)
  const submitLoading = ref(false)
  const userList = ref<UserInfo[]>([])
  const roleList = ref<RoleInfo[]>([])
  const selectedUsers = ref<UserInfo[]>([])
  const total = ref(0)
  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const userFormRef = ref<FormInstance>()

  // 搜索表单
  const searchForm = reactive<UserSearchParams>({
    page: 1,
    limit: 10,
    keyword: '',
    roleId: undefined,
    status: undefined
  })

  // 日期范围
  const dateRange = ref<[string, string] | null>(null)

  // 用户表单 - 修改默认状态为0（启用）
  const userForm = reactive<UserFormData>({
    username: '',
    nickname: '',
    password: '',
    email: '',
    phone: '',
    roleId: 0,
    status: 0  // 改为0（启用）作为默认值
  })

  // 表单验证规则
  const formRules: FormRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 5, max: 20, message: '用户名长度在 5 到 20 个字符', trigger: 'blur' },
      { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
    ],
    nickname: [
      { required: true, message: '请输入用户昵称', trigger: 'blur' },
      { min: 5, max: 20, message: '昵称长度在 5 到 20 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    email: [
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    phone: [
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    roleId: [
      { required: true, message: '请选择角色', trigger: 'change' }
    ],
    status: [
      { required: true, message: '请选择状态', trigger: 'change' }
    ]
  }

  // 计算属性
  const dialogTitle = computed(() => isEdit.value ? '编辑用户' : '新增用户')

  // 状态处理方法
  const getStatusValue = (status: any) => {
    // 确保返回的是数字类型，并且符合我们的映射规则
    const numStatus = Number(status)
    console.log('原始状态值:', status, '转换后:', numStatus)
    return numStatus
  }

  const getStatusText = (status: any) => {
    const numStatus = Number(status)
    return numStatus === 0 ? '启用' : '禁用'
  }

  // 方法
  const formatDate = (dateString: string) => {
    if (!dateString) return '-'
    return new Date(dateString).toLocaleString('zh-CN')
  }

  const getRoleTagType = (roleId: number) => {
    const typeMap: Record<number, string> = {
      1: 'danger', // 超级管理员
      2: 'warning', // 管理员
      3: 'success', // 普通用户
    }
    return typeMap[roleId] || 'info'
  }

  // 获取用户列表
  const getUserList = async () => {
    loading.value = true
    try {
      // 处理日期范围
      if (dateRange.value) {
        searchForm.startTime = dateRange.value[0]
        searchForm.endTime = dateRange.value[1]
      } else {
        searchForm.startTime = undefined
        searchForm.endTime = undefined
      }

      const response = await getUserListAPI(searchForm)
      if (response.code === 200) {
        userList.value = response.data.list
        total.value = response.data.total

        // 调试：打印用户列表的状态值
        console.log('获取到的用户列表:', userList.value.map(user => ({
          id: user.id,
          username: user.username,
          status: user.status,
          statusType: typeof user.status
        })))
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      console.error('获取用户列表失败:', error)
      ElMessage.error('获取用户列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取角色列表
  const getRoleList = async () => {
    try {
      const response = await getRoleListAPI()
      if (response.code === 200) {
        roleList.value = response.data
      }
    } catch (error) {
      console.error('获取角色列表失败:', error)
    }
  }

  // 搜索
  const handleSearch = () => {
    searchForm.page = 1
    getUserList()
  }

  // 重置
  const handleReset = () => {
    Object.assign(searchForm, {
      page: 1,
      limit: 10,
      keyword: '',
      roleId: undefined,
      status: undefined
    })
    dateRange.value = null
    getUserList()
  }

  // 分页
  const handleSizeChange = (size: number) => {
    searchForm.limit = size
    searchForm.page = 1
    getUserList()
  }

  const handleCurrentChange = (page: number) => {
    searchForm.page = page
    getUserList()
  }

  // 选择变化
  const handleSelectionChange = (selection: UserInfo[]) => {
    selectedUsers.value = selection
  }

  // 状态变化 - 修改参数结构
  const handleStatusChange = async (row: UserInfo, newStatus: number) => {
    console.log('状态切换:', {
      userId: row.id,
      username: row.username,
      oldStatus: row.status,
      newStatus: newStatus
    })

    // 先更新本地状态
    const oldStatus = row.status
    row.status = newStatus

    try {
      const response = await updateUserStatusAPI(row.id, newStatus)
      if (response.code === 200) {
        ElMessage.success('状态更新成功')
      } else {
        // 还原状态
        row.status = oldStatus
        ElMessage.error(response.message)
      }
    } catch (error) {
      // 还原状态
      row.status = oldStatus
      ElMessage.error('状态更新失败')
    }
  }

  // 重置表单 - 修改默认状态为0（启用）
  const resetForm = () => {
    Object.assign(userForm, {
      username: '',
      nickname: '',
      password: '',
      email: '',
      phone: '',
      roleId: 0,
      status: 0  // 改为0（启用）作为默认值
    })
    userFormRef.value?.clearValidate()
  }

  // 新增用户
  const handleAdd = () => {
    resetForm()
    isEdit.value = false
    dialogVisible.value = true
  }

  // 编辑用户
  const handleEdit = (row: UserInfo) => {
    resetForm()
    isEdit.value = true
    Object.assign(userForm, {
      id: row.id,
      username: row.username,
      nickname: row.nickname,
      email: row.email,
      phone: row.phone,
      roleId: row.roleId,
      status: row.status
    })
    dialogVisible.value = true
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!userFormRef.value) return

    try {
      await userFormRef.value.validate()
      submitLoading.value = true

      const api = isEdit.value ? updateUserAPI : addUserAPI
      const response = await api(userForm)

      if (response.code === 200) {
        ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
        dialogVisible.value = false
        getUserList()
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  }

  // 删除用户
  const handleDelete = async (row: UserInfo) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除用户 "${row.nickname}" 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      const response = await deleteUserAPI(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        getUserList()
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedUsers.value.length === 0) {
      ElMessage.warning('请选择要删除的用户')
      return
    }

    try {
      await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
        '批量删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      const ids = selectedUsers.value.map(user => user.id)
      const response = await batchDeleteUserAPI({ ids })

      if (response.code === 200) {
        ElMessage.success('批量删除成功')
        getUserList()
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('批量删除失败')
      }
    }
  }

  // 生命周期
  onMounted(() => {
    getRoleList()
    getUserList()
  })
</script>

<style scoped>
  .user-container {
    padding: 20px;
  }

  .search-card {
    margin-bottom: 20px;
  }

  .search-form {
    margin-bottom: 0;
  }

  .main-card {
    min-height: 600px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-header h3 {
    margin: 0;
    color: #333;
  }

  .header-buttons {
    display: flex;
    gap: 10px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .user-form {
    padding: 0 20px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  .status-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
  }

  .status-debug {
    font-size: 12px;
    color: #666;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .user-container {
      padding: 10px;
    }

    .search-form {
      flex-direction: column;
    }

    .search-form .el-form-item {
      margin-right: 0;
      margin-bottom: 15px;
    }

    .card-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;
    }

    .header-buttons {
      width: 100%;
      justify-content: flex-start;
    }
  }
</style>
